﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Serialization;
namespace System.Map
{
    public static partial class IpLocation
    {
        private const string url ="http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip={0}&coor=bd09ll";

        public static Task<IpLocationResult> LocationAsync(this string ip)
        {
            var webClient = new WebClient();

            var task = webClient.DownloadDataTaskAsync(string.Format(url, ip)).ContinueWith(netTask =>
                {
                    IpLocationResult result = null;
                    if (netTask.IsCompleted && netTask.Exception == null)
                        result = netTask.Result.JsonDeSerializer<IpLocationResult>();
                    else
                    {
                        result = new IpLocationResult();
                    }
                    webClient.Dispose();
                    return result;
                });
            return task;
        }
        public static IpLocationResult Location(this string ip)
        {
            using (var webClient = new WebClient())
            {
                var buffer = webClient.DownloadData(string.Format(url, ip));
                return buffer.JsonDeSerializer<IpLocationResult>();
            }
        }
    }

    public class IpLocationResult
    {
        public string Address { get; set; }

        [JsonProperty("content")]
        public Content Content { get; set; }
    }
    public class Content
    {
        [JsonProperty("address_detail")]
        public DetailAddress DetailAddress { get; set; }
        public Point Point { get; set; }
    }
    public class DetailAddress
    {
        /// <summary>
        /// 省
        /// </summary>
        public string Province { get; set; }

        /// <summary>
        /// 市
        /// </summary>
        public string City { get; set; }

        /// <summary>
        /// 区
        /// </summary>
        public string District { get; set; }
        /// <summary>
        /// 城市代码
        /// </summary>
        [JsonProperty("city_code")]
        public string CityCode { get; set; }
        /// <summary>
        /// 街道
        /// </summary>
        public string Street { get; set; }

        /// <summary>
        /// 门牌号码
        /// </summary>
        [JsonProperty("Street_Number")]
        public string StreetNumber { get; set; }
        /// <summary>
        /// 详细地址:省市区县街道门牌号
        /// </summary>
        public string ToDetailAddress()
        {
            return string.Concat(Province, City, District, Street, StreetNumber);
        }
        
    }
}